import React, {Fragment, ReactElement, ReactNode, useCallback} from 'react';
import {StyleProp, Text, View, ViewStyle, StyleSheet} from 'react-native';
import color from 'variables/color';

interface Header {
  title: string;
  rightTitle?: ReactNode;
}

export interface SimpleTableProps<T = string> {
  /** 列表的数据 */
  listData?: {
    /**表头 */
    header?: Header;
    /** 表格体 */
    body?: Array<T[]>;
  };
  /** 行是否有边框 */
  rowBorder?: boolean;
  /** 自定渲染表格，单个数据 */
  renderItem?: (str: T) => ReactElement;
  containerStyle?: StyleProp<ViewStyle>;
}

export function SimpleTable<T = string>(props: SimpleTableProps<T>) {
  const {listData, rowBorder, renderItem, containerStyle} = props;
  const {header, body} = listData ?? {};

  const {title, rightTitle} = header ?? {};

  const renderTemplate = useCallback(
    (str: T) =>
      renderItem?.(str) ?? (
        <Text style={{textAlign: 'center', fontSize: 12, fontWeight: '500'}}>
          {str}
        </Text>
      ),
    [renderItem],
  );

  return (
    <View style={[styles.container, containerStyle]}>
      {header && (
        <View style={[styles.header]}>
          {!!title && <Text style={styles.headerTitle}>{title}</Text>}
          {!!rightTitle &&
            (typeof rightTitle === 'string' ? (
              <Text style={styles.rightTitle}>{rightTitle}</Text>
            ) : (
              rightTitle
            ))}
        </View>
      )}
      {body?.map((outer, outerIndex) => (
        <Fragment key={outerIndex}>
          <View style={[styles.bodyItem]}>
            {outer?.map((item, index) => (
              <View
                style={[styles.item, {padding: !!renderItem ? 0 : 4}]}
                key={index}>
                {renderTemplate(item)}
              </View>
            ))}
          </View>
          {rowBorder && body.length !== outerIndex + 1 && (
            <View style={{marginHorizontal: 0, height: 1, flex: 1}} />
          )}
        </Fragment>
      ))}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    borderColor: '#D8D8D8',
    borderStyle: 'solid',
    borderWidth: StyleSheet.hairlineWidth,
    borderRadius: 4,
    overflow: 'hidden',
  },
  header: {
    minHeight: 40,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: 'rgba(0, 0, 0, 0.05)',
    paddingHorizontal: 16,
  },
  headerTitle: {
    fontSize: 13,
    lineHeight: 40,
    color: color.TEXT_MAIN,
    fontWeight: '500',
  },
  rightTitle: {
    color: color.TEXT_MAIN,
    fontSize: 13,
    textDecorationLine: 'underline',
  },
  bodyItem: {
    flexDirection: 'row',
    alignItems: 'center',
    minHeight: 40,
    backgroundColor: 'transparent',
  },
  item: {
    flex: 1,
  },
});
